# -*- utf-8 -*-
# @Time: 2021/7/26 0:03
# @Author: CACode
from django.core.mail import EmailMultiAlternatives

import requests
from ajson import aj
from django.http import Http404
from rest_framework import status
from rest_framework.authentication import SessionAuthentication, BasicAuthentication
from rest_framework.exceptions import ParseError
from rest_framework.generics import GenericAPIView
from rest_framework.pagination import PageNumberPagination
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework.viewsets import ViewSetMixin
from rest_framework_jwt.authentication import JSONWebTokenAuthentication


class Result:
    """
    响应返回
    """

    @staticmethod
    def success(**kwargs):
        payload = {
            'code': status.HTTP_200_OK,
            'message': 'ok'
        }
        payload.update(kwargs)
        return Response(payload, status=status.HTTP_200_OK)

    @staticmethod
    def error(**kwargs):
        payload = {
            'code': status.HTTP_500_INTERNAL_SERVER_ERROR,
            'message': 'error'
        }
        payload.update(kwargs)
        return Response(data=payload, status=status.HTTP_200_OK if 'code' not in kwargs.keys() else kwargs['code'])


class MyPageNumber(PageNumberPagination):
    page_size = 10  # 每页显示多少条
    page_size_query_param = 'size'  # URL中每页显示条数的参数
    page_query_param = 'page'  # URL中页码的参数
    max_page_size = None  # 最大页码数限制


class GetObjectMixin:
    """
    从请求体中获取id，用于替换gengericapiview中的get_object方法
    """

    def get_object(self, field="id"):
        obj_id = self.request.data.get(field, None)
        try:
            self.queryset = self.queryset or self.get_queryset()
            return self.queryset.get(id=int(obj_id))
        except self.queryset.model.DoesNotExist:
            raise Http404
        except (ValueError, TypeError):
            raise ParseError("参数不正确,请带上id")


class CustomGenericViewSet(GetObjectMixin, ViewSetMixin, GenericAPIView):
    """将类转换成可以多个方法不同请求的类"""
    pass


class Request:
    @staticmethod
    def get(url, json_format=True, params=None, **kwargs):
        req_obj = requests.get(url, params, **kwargs)
        req_obj.encoding = 'utf8'
        text = req_obj.text
        if json_format:
            return aj.load(text)
        return text

    @staticmethod
    def post(url, data=None, json=None, **kwargs):
        req_obj = requests.post(url, data, json, **kwargs)
        req_obj.encoding = 'utf8'
        return req_obj


class EmailUtil:
    @staticmethod
    def send_sms(config):
        msg = EmailMultiAlternatives(config['title'],  # 标题
                                     config['message'],  # 标题旁边的描述
                                     config['from_email'],  # 谁发
                                     [i['name'] for i in config['EmailRecipient']])  # 发给谁
        msg.attach_alternative(config['content'], "text/html")
        msg.send()


class NeedLoginView(APIView):
    authentication_classes = [JSONWebTokenAuthentication, SessionAuthentication, BasicAuthentication]
    permission_classes = [IsAuthenticated]


class ExecuteSql:
    def get_dataframe_data(self, data, columns=None):
        ret = []
        res_data = data.to_dict('records')
        for item in res_data:
            payload = {i: {} for i in columns}
            for key in columns:
                for k, v in item.items():
                    if len(k) >= len(key):
                        if k[:len(key)] == key:
                            payload[key][k[len(key) + 1:]] = v
            ret.append(payload)
        return ret
